package com.dashan;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * 生成接口的代理类
 * @author b5m
 *
 */
public class RpcClient {
	
	public static Object createProxyObj(final Class<?> target) {
		
		return Proxy.newProxyInstance(target.getClassLoader(), new Class[]{target}, new InvocationHandler() {
			
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				//连接服务
				Socket socket = null;
				ObjectOutputStream oos = null;
				//接收响应
				InputStream inputStream = null;
				ObjectInputStream ois = null;
				Object result;
				try {
					socket = new Socket("127.0.0.1", 8888);
					OutputStream outputStream = socket.getOutputStream();
					oos = new ObjectOutputStream(outputStream);
					//发送请求参数
					oos.writeUTF(target.getName());
					oos.writeUTF(method.getName());
					oos.writeObject(method.getParameterTypes());
					oos.writeObject(args);
					inputStream = socket.getInputStream();
					ois = new ObjectInputStream(inputStream);
					result = ois.readObject();
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					throw e;
				} finally {
					if(ois != null) {
						ois.close();
					}
					if(inputStream != null) {
						inputStream.close();
					}
					if(oos != null) {
						oos.close();
					}
					if(socket != null) {
						socket.close();
					}
				}
			}
		});
	}
}
